# 定义'火车'
class Train:
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next
# 定义'火车头'
class List():
    def __init__(self):
        self.head = Train()
        self.length = 0

    def insert(self, pos, data):
        if pos >= 0 and pos <= self.length:

            # 找 pos 的位置
            tmp = self.head
            while pos > 0:
                tmp = tmp.next
                pos -= 1

            # pos 后面插入newlist
            newlist = Train()
            newlist.data = data
            newlist.next = tmp.next
            tmp.next = newlist
            self.length += 1

#末尾添加
    def append(self, data):
        self.insert(self.length, data)

#根据pos删除
    def remove(self, pos):
        assert pos < self.length

        tmp = self.head
        while pos > 0:
            tmp = tmp.next
            pos -= 1
        # 删除
        if tmp.next is not None:
            tmp.next = tmp.next.next
            self.length -= 1

#遍历
    def alllist(self):
        tmp = self.head.next
        while tmp is not None:
            yield tmp.data
            tmp = tmp.next

    def __iter__(self):
        return self.alllist()

#更改元素
    def update(self, pos, data):
        tmp = self.head
        while pos > 0:
            tmp = tmp.next
            pos -= 1

        tmp.data = data

#根据data删除
    def deletelist(self, data):
        tmp = self.head
        while tmp is not None and tmp.next is not None:
            if tmp.next.data == data:
                tmp.next = tmp.next.next
            tmp = tmp.next

        # i = 0
        # tmp = self.head
        # while i < self.length:
        #     tmp = tmp.next
        #     if tmp.data == data:
        #         self.remove(i)
        #         self.length -= 1
        #     i += 1


if __name__ == '__main__':

    l = List()
    l.append(1)
    l.append(2)
    l.append(3)
    l.append(4)
    l.append(5)
    l.append(155)

    for x in l.alllist():
        print(x)

    print('insert 4th at 100')
    l.insert(4, 100)
    for x in l.alllist():
        print(x)

    print('remove 4th')
    l.remove(3)
    print('remove 7th')
    l.remove(6)
    for x in l.alllist():
        print(x)

    print('update 3th 255')
    l.update(3, 255)
    for x in l.alllist():
        print(x)

    print('删除指定data')
    l.deletelist(155)
    l.deletelist(1)
    for x in l.alllist():
        print(x)

